//
//  ViewController.swift
//  XFDownloadDemo
//
//  Created by mac on 2018/11/5.
//  Copyright © 2018 zeroLu. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    private var dataSource = ["http://dpm3.oss-cn-shenzhen.aliyuncs.com/prod/course/section/video/2018-11-01/5eaa8c6264c1b7cc9cac92c1750ecb49.mp4",
                              "http://jzdp.oss-cn-shenzhen.aliyuncs.com/prod/course/section/video/2018-06-26/b41ad28cd37f1d741e3341cb7f396cf1.mp4",
                              "http://jzdp.oss-cn-shenzhen.aliyuncs.com/prod/course/section/video/2018-07-09/f34cb0d05dbc68359854d9531a62bbb2.mp4",
                              "http://bcm3.oss-cn-shenzhen.aliyuncs.com/prod/course/section/video/2018-07-04/6c9fc235f054b9613bf11f9a077726ac.mp4"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        
        tableView.dataSource = self
        
        tableView.register(UINib(nibName: "DownloadCell", bundle: nil), forCellReuseIdentifier: DownloadCell.description())
        
        XFDownloadManager.shared.maxConcurrentCount = 1
    }
    
    
    func setupData() {
        
        for urlString in dataSource {
            XFDownloadManager.shared.download(url: URL(string: urlString), stateBlock: { [weak self] (currentUrl, state) in
                if state == XFDownloadState.running {
                    print("~~~~~~~~~~~~\(currentUrl)~~~~~~~~~正在下载")
                } else if state == XFDownloadState.completed {
                    self?.updateDownloadCell(currentUrl, "已下载完成", 1.0)
                }
            }, progressBlock: { [weak self] (currentUrl, receivedSize, expectedSize, progress) in
                
                let received = receivedSize.toStringSize()
                
                let expected = expectedSize.toStringSize()
                
                self?.updateDownloadCell(currentUrl, "\(received)/\(expected)", progress)
                
            }) { (finishUrl, success, sandBoxPath, error) in
                if let _error = error {
                    print(_error)
                } else {
                    if success {
                        print("~~~~~~~~~~~~\(finishUrl)~~~~~~~~~正在下载")
                    }
                }
            }
        }
    }
    
    func downloadError(_ url: URL?, _ error: Error?) {
        DispatchQueue.main.async {
            
            if self.tableView.isDragging && self.tableView.isDecelerating {return}
            
            guard let cell = (self.tableView.visibleCells as? [DownloadCell])?.filter({ $0._url == url }).first else {
                return
            }
            
            cell.updateProgress(progressText: "网络错误", progress: 0)
            
        }
    }
    
    func updateDownloadCell(_ url: URL?, _ progressText: String, _ progress: Float) {
        
        DispatchQueue.main.async {
            
            if self.tableView.isDragging && self.tableView.isDecelerating {return}
            
            guard let cell = (self.tableView.visibleCells as? [DownloadCell])?.filter({ $0._url == url }).first else {
                return
            }
            
            cell.updateProgress(progressText: progressText, progress: progress)
            
        }
        
    }
    
    @IBAction func didSuspenedAllAction(_ sender: Any) {
        XFDownloadManager.shared.suspendDownloadAll()
    }
    
    @IBAction func didBeginAllAction(_ sender: Any) {
        //        XFDownloadManager.shared.resumeDownloadAll()
        setupData()
        
        print(XFDownloadManager.shared._downloadingModels)
    }
    
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = (tableView.dequeueReusableCell(withIdentifier: DownloadCell.description()) as? DownloadCell) ?? DownloadCell()
        
        let urlString = dataSource[indexPath.row]
        
        let url = URL(string: urlString)
        
        cell.setupData(name: url?.fileName(), url: url)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let urlString = dataSource[indexPath.row]
        
        let url = URL(string: urlString)
        
        XFDownloadManager.shared.autoBeginOrSuspend(url, progressBlock: { [weak self] (currentUrl, receivedSize, totalLength, progress) in
            
            let received = receivedSize.toStringSize()
            
            let expected = totalLength.toStringSize()
            
            self?.updateDownloadCell(currentUrl, "\(received)/\(expected)", progress)
            
        })
    }
}

